package com.baiyun.utils;

import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

@Data
@Component
@ConfigurationProperties(prefix = "markerhub.jwt")
public class JwtUtils {

    private long expire;
    private String secret;
    private String header;

    //生成jwt(token)
    public String generateToken(String username){
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire);
        return Jwts.builder()
               .setHeaderParam("typ","JWT")
               .setSubject(username)   //载荷
               .setIssuedAt(nowDate)
                .setExpiration(expireDate)   //过期时间
                .signWith(SignatureAlgorithm.HS512,secret)    //密钥
                .compact();
    }
    // 解析jwt
    public Claims getClaimByToken(String jwt) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    // jwt是否过期
    public boolean isTokenExpired(Date expiration,Date lastLoginDate,Date issueDate) {
        //token创建时间小于数据库记录的最后一次登出时间 过期
        if(lastLoginDate == null){
            return expiration.before(new Date());
        }else{
            return issueDate.before(lastLoginDate);
        }
    }
}
